<template>
  <div>
    <Layout class="app-frame" v-if="!loading" :siderCollapsed="siderCollapsed" siderFixed>
      <Sider theme="dark" style="background-color: #001529">
        <div class="app-menu">
          <div class="app-logo" style="background:white; height: 54px;overflow: hidden;">
            <router-link to="/">
              <div style="display: flex;align-items: center; height: 54px; width: 200px;">
                  <span class="app-logo-icon"
                        style="background: url(img/logo.png);margin-left:8px; width:45px;height:45px; background-size: 100% 100%;display: inline-block;
    margin-right: 10px;margin-top: 4px;"></span>
                <span class="app-logo-text" style="color: var(--pc);lex: 1;font-size: 20px;flex:1;">{{ title }}</span>
              </div>
            </router-link>
          </div>
          <div :class="{menu_expand:!siderCollapsed}">
            <Menu :datas="user.menu" :mode="siderCollapsed?'collapse':'vertical'" @select="menuSelect" ref='menu'
                  className="h-menu-dark" style="background-color: #001529" accordion></Menu>
            <div class="app-menu-mask" @click="siderCollapsed=true"></div>
          </div>
        </div>
      </Sider>
      <Layout headerFixed>
        <HHeader theme="white">
          <div class="app-header" style="display: flex;">
            <div style="width:50px;float:left;">
              <Button :icon="siderCollapsed ? 'icon-align-right':'icon-align-left'" size="l" noBorder class="font20"
                      @click="siderCollapsed=!siderCollapsed"></Button>
            </div>
            <!-- 顶部模块菜单 -->
            <div style="flex: 1" class="top-menu-pc">
              <Breadcrumb :datas="breadcrumb"></Breadcrumb>
            </div>
            <component v-if="topbar" :is="TopBar"></component>
            <div class="float-right app-header-info">
              <div class="themes">
                <div style="background-color:#409eff" @click="setTheme('blue')"></div>
                <div style="background-color:#45b984" @click="setTheme('green')"></div>
                <div style="background-color:#d36eb0" @click="setTheme('purple')"></div>
                <div style="background-color:#cf5e4d" @click="setTheme('red')"></div>
              </div>
              <DropdownMenu className="app-header-dropdown" trigger="hover" offset="0,5" :width="150"
                            placement="bottom-end" :datas="userMenu" @clickItem="userMenuClick">
                <span>{{ user.name }}({{ user.username }})</span>
              </DropdownMenu>
            </div>
          </div>
        </HHeader>
        <Content>
          <div class="app-frame-content" style="height:100%">
            <!--            &lt;!&ndash; <keep-alive> &ndash;&gt;-->
            <!--            <transition name="fade">-->
            <!--              <router-view/>-->
            <!--            </transition>-->
            <RouterView v-slot="{ Component }">
              <transition name="fade">
                <component :is="Component"/>
              </transition>
            </RouterView>
            <!-- </keep-alive> -->
          </div>
        </Content>
      </Layout>
    </Layout>
    <Modal v-model="changePwd" middle hasDivider>
      <template #header>修改密码</template>
      <div width="300">
        <Form
            :labelWidth="110"
            ref="pwdForm"
            :rules="pwdRules"
            :model="pwds"
            class="title-suffix"
        >
          <FormItem label="旧密码" prop="OldPassword" required>
            <Input type="password" v-model="pwds.OldPassword"/>
          </FormItem>
          <FormItem label="新密码" prop="Password" required>
            <Input type="password" v-model="pwds.Password"/>
          </FormItem>
          <FormItem label="重复新密" prop="ConfirmPassword" required>
            <Input type="password" v-model="pwds.ConfirmPassword"/>
          </FormItem>
        </Form>
      </div>
      <template #footer class="text-right">
        <Button @click="updatePwd">确定</Button>
      </template>
    </Modal>
  </div>
</template>
<script setup>
import {ajax, mapActions,loadComponent} from 'framework'
import {ref, reactive,defineAsyncComponent} from 'vue'

const title = document.title || 'Easy Admin'
const topbar=window._configs['PlatformConfig.TopBar']
const TopBar=defineAsyncComponent(()=>loadComponent(topbar))
let {user, theme} = F.mapState(['user', 'theme'])
let tempSelect;
const pwdRules = {
  rules: {
    Password: {
      maxLen: 18,
      minLen: 5
    }
  },
  combineRules: [{
    refs: ['Password', 'ConfirmPassword'],
    valid(a, b) {
      if (a != b) {
        return "两次输入密码必须相同";
      }
      return true;
    }
  }]
}
let userMenu = reactive([
  {key: 'pwd', title: '修改密码', icon: 'h-icon-lock'},
  {key: 'logout', title: '退出登录', icon: 'h-icon-outbox'}
])
const route = VueRouter.useRoute()
const router = VueRouter.useRouter()
let changePwd = ref(false),
    appName = ref(''),
    userName = ref(''),
    loading = ref(false),
    siderCollapsed = ref(localStorage.siderCollapsed=="true"),
    {setTheme} = mapActions(['setTheme']),
    pwdForm = ref(null),
    pwds = reactive({
      OldPassword: "",
      Password: "",
      ConfirmPassword: ""
    }),
    currentTop = ref({}),
    breadcrumb = ref([]),
    menu = ref(null)

Vue.watch(siderCollapsed,(nv)=>{
  localStorage.siderCollapsed=nv;
})
VueRouter.onBeforeRouteUpdate(to => {
  initSelect(to)
});
Vue.onMounted(initSelect)

function updatePwd() {
  let validResult = pwdForm.value.valid();
  if (validResult.result) {
    if (pwds.Password != pwds.ConfirmPassword) {
      HeyUI.message("两次输入的密码不一致");
      return
    }
    //  console.log(toRaw(pwds))
    ajax.formPost("system/changePassword", pwds).then(r => {
      HeyUI.message(r.message)
      changePwd.value = false
    })
  }
}

function initSelect(_route = route) {
  function findPath(data, name) {
    for (let it of data) {
      if (it.key == name) {
        return [{title: it.title}]
      }
      if (it.children) {
        let ret = findPath(it.children, name)
        if (ret.length > 0) {
          return [{title: it.title}, ...ret]
        }
      }
    }
    return []
  }

  let name = _route.name;
  if (name && menu.value) {
    tempSelect=name
    menu.value.select(name);
    let dt = findPath(user.value.menu, name)
    breadcrumb.value = dt;
  } else {
    breadcrumb.value = []
  }
}

function userMenuClick(data) {
  if (data == "logout") {
    ajax.get('system/logout').then((r) => {
      location.hash="/login"
      setTimeout(()=>location.reload(),1)
    })
  } else if (data == "pwd") {
    Object.assign(pwds, {
      OldPassword: "",
      Password: "",
      ConfirmPassword: ""
    })
    changePwd.value = true
  }
}

function menuSelect(m) {
  if (route.name != m.key) {
    if(m.path.startsWith("_blank:")){
    //  open(m.path.substr(7),'_blank')
      menu.value.select(tempSelect)
    }else{
      tempSelect=m.name
      router.push({name: m.key})
    }

  }
}
</script>

<style lang="less">
.app-frame {
  .app-menu {
    display: flex;
    flex-direction: column;
    height: 100%;

    .h-menu {
      margin-top: 10px;
    }
  }

  .app-logo {
    margin-bottom: 0
  }

  .menu_expand {
    position: relative;
    overflow-y: auto;
    flex: 1;

    .h-menu {
      position: absolute;
    }
  }

  .themes {
    display: inline-block;
    line-height: 50px;
    height: 50px;
    vertical-align: bottom;

    div {
      cursor: pointer;
      height: 20px;
      width: 20px;
      display: inline-block;
      margin-right: 10px;
      border-radius: 3px;
      margin-top: 13px;
      float: left;
    }
  }
}
</style>
